#include "http/http_connection.h"
#include "log.h"
#include "iomanager.h"

static johnsonli::Logger::ptr g_logger = LOG_ROOT();

void test_pool()
{
    johnsonli::http::HttpConnectionPool::ptr pool(new johnsonli::http::HttpConnectionPool("www.sylar.top", "", 80, false, 10, 1000 * 30, 5));
    
    johnsonli::IOManager::GetThis()->addTimer(1000, [pool](){
        auto r = pool->doGet("/blog/", 300);
        LOG_INFO(g_logger) << r->toString();
    }, true);
}

void run()
{
    //创建socket
    johnsonli::Address::ptr addr = johnsonli::Address::LookupAnyIPAddress("www.baidu.com:80");
    johnsonli::Socket::ptr sock = johnsonli::Socket::CreateTCP(addr);
    
    //建立连接
    sock->connect(addr);

    //httpconnection
    johnsonli::http::HttpConnection::ptr conn(new johnsonli::http::HttpConnection(sock));  

    //发送请求      
    johnsonli::http::HttpRequest::ptr req(new johnsonli::http::HttpRequest);
    req->setPath("/");
    req->setHeader("host", "www.baidu.com");
    LOG_INFO(g_logger) << "req:" << std::endl
        << *req;

    conn->sendRequest(req);

    //接收响应
    auto rsp = conn->recvResponse();

    if(!rsp) {
        LOG_INFO(g_logger) << "recv response error";
        return;
    }
    
    LOG_INFO(g_logger) << "rsp:" << std::endl
        << *rsp;
    
    std::ofstream ofs("rsp.dat");
    ofs << *rsp;

    LOG_INFO(g_logger) << "=========================";
    
  
    auto r = johnsonli::http::HttpConnection::DoGet("http://www.baidu.com:80", 300, false); //必须设置端口号？？？
    LOG_INFO(g_logger) << "result=" << r->result
        << " error=" << r->error
        << " rsp=" << (r->response ? r->response->toString() : "");


    LOG_INFO(g_logger) << "=========================";

    //test_pool();
    
}

int main()
{
    johnsonli::IOManager iom(1);
    iom.schedule(run);
    
    return 0;
}